'use strict'

const {logger} = require('ee-core/log')
const {BrowserWindow} = require('electron')
const {appService} = require('../service/app')
const {restoreMainWindow} = require('ee-core/electron/window')

/**
 * 窗口控制
 */
class WindowController {
    /**
     * 关闭窗口 (ipc)
     */
    async close(args, event) {
        const currentWindow = BrowserWindow.fromWebContents(event.sender)
        let ret

        try {
            currentWindow.close()
            ret = {
                state: true,
                message: 'Window closed.'
            }
            logger.info(WindowController.toString(), ret.message)
        } catch {
            ret = {
                state: false,
                message: 'Window closing failure.'
            }
            logger.error(WindowController.toString(), ret.message)
        }

        return ret
    }

    /**
     * 窗口最大化/还原 (ipc)
     */
    async restore(args, event) {
        const currentWindow = BrowserWindow.fromWebContents(event.sender)
        const isMaximized = currentWindow.isMaximized()

        if (isMaximized) {
            currentWindow.unmaximize()
        } else {
            currentWindow.maximize()
        }

        if (args && args.appConfigProp) {
            appService[args.appConfigProp] = !isMaximized
        }

        return !isMaximized
    }

    /**
     * 窗口最小化 (ipc)
     */
    async minimum(args, event) {
        const currentWindow = BrowserWindow.fromWebContents(event.sender)
        if (currentWindow.isMinimized()) {
            return
        }

        currentWindow.minimize()
    }

    /**
     * 窗口置顶/取消置顶 (ipc)
     */
    async pin(args, event) {
        const currentWindow = BrowserWindow.fromWebContents(event.sender)
        const boolean = !currentWindow.isAlwaysOnTop()

        currentWindow.setAlwaysOnTop(boolean)
        if (args && args.appConfigProp) {
            appService[args.appConfigProp] = boolean
        }

        return boolean
    }

    /**
     * 设置窗口缩放 (:字体大小)
     */
    async setZoomFactor(args) {
        //保存配置
        appService.appZoomFactor = args
        const allOpened = BrowserWindow.getAllWindows()
        allOpened.forEach((window) => {
            window.webContents.setZoomFactor(args)
        })
    }

    /**
     * 聚焦主窗口(从其他窗口聚焦到主窗口)
     */
    async focusMainWindow() {
        restoreMainWindow()
    }

    /**
     * 更新所有窗口背景色
     */
    async setAllBackgroundColor(args) {
        const allWindow = BrowserWindow.getAllWindows()
        allWindow.forEach((win) => {
            win.setBackgroundColor(args)
        })
    }
}

WindowController.toString = () => '[class WindowController]'
module.exports = WindowController